package com.yiqi.liebang.feature.home.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baiiu.filter.ClassifyBo;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.T;
import com.yiqi.liebang.R;
import com.yiqi.liebang.entity.bo.LifeMenuSection;
import com.yiqi.liebang.entity.bo.SearchFriendBo;
import com.yiqi.liebang.feature.home.contract.ClassifyContract;
import com.yiqi.liebang.feature.home.dependencies.classsify.ClassifyPresenterModule;
import com.yiqi.liebang.feature.home.dependencies.classsify.DaggerClassifyComponent;
import com.yiqi.liebang.feature.home.view.adapter.ClassifyAdapter;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;

import butterknife.BindView;

public class ClassifyActivity extends BaseActivity implements ClassifyContract.View, OnRefreshListener, BaseQuickAdapter.OnItemChildClickListener, Toolbar.OnMenuItemClickListener {

    @Inject
    ClassifyContract.Presenter mPresenter;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.rv_classify)
    RecyclerView mRvClassify;
    @BindView(R.id.smartRefesh)
    SmartRefreshLayout mSmartRefesh;
    List<String> mStrings = new ArrayList<>();
    @BindView(R.id.rv_classify_select)
    RecyclerView mRvClassifySelect;
    @BindView(R.id.view_label)
    LinearLayout mViewLabel;
    @BindView(R.id.tv_show_label_count)
    TextView mTvShowLabelCount;

    private boolean isSelect = false;
    List<ClassifyBo> mData;
    private LabelAdpter mLabelAdpter;
    ArrayList<ClassifyBo> mLabelList = new ArrayList<>();
    ClassifyAdapter sectionAdapter;
    List<LifeMenuSection> list;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_classify;
    }

    @Override
    protected void initInjector() {
        DaggerClassifyComponent.builder().classifyPresenterModule(new ClassifyPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        mRvClassifySelect.setLayoutManager(new GridLayoutManager(this, 4));
        isSelect = this.getIntent().getBooleanExtra("isSelect", false);
        if (isSelect) {
            mLabelAdpter = new LabelAdpter();
            mLabelAdpter.bindToRecyclerView(mRvClassifySelect);
            mLabelAdpter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    mLabelList.remove(position);
                    mLabelAdpter.notifyDataSetChanged();
                    mTvShowLabelCount.setText(Html.fromHtml("已选择标签：<font color=\"#2AA0F8\">" + mLabelAdpter.getData().size() + "</font>"));
                }
            });
            mViewLabel.setVisibility(View.VISIBLE);
            mToolbar.inflateMenu(R.menu.menu_save);
            initToolBar(mToolbar, "选择职业标签", true, true);

        } else {
            mViewLabel.setVisibility(View.GONE);
            initToolBar(mToolbar, "全部分类", true, true);
        }

        mRvClassify.setLayoutManager(new GridLayoutManager(this, 4));
    }

    @Override
    protected void initData() {
        mPresenter.getClassifyData();
        mLabelList = this.getIntent().getParcelableArrayListExtra("classify");
        if (mLabelList != null && mLabelList.size() > 0) {
            mLabelAdpter.setNewData(mLabelList);
            mTvShowLabelCount.setText(Html.fromHtml("已选择标签：<font color=\"#2AA0F8\">" + mLabelAdpter.getData().size() + "</font>"));
        }
    }

    @Override
    protected void initEvent() {
        mSmartRefesh.setEnableLoadMore(false);
        mSmartRefesh.setOnRefreshListener(this);
        mToolbar.setOnMenuItemClickListener(this);
    }

    @Override
    public void showUserSuccess(String classifyBos) {

    }

    @Override
    public void showUserError(String classifyBos) {

    }

    @Override
    public void showSuccess(List<ClassifyBo> classifyBos) {
        mData = classifyBos;
        if (mLabelList != null && mLabelList.size() > 0) {
            for (int i = 0; i < mLabelList.size(); i++) {
                for (int j = 0; j < mData.size(); j++) {
                    ClassifyBo classifyBo = mData.get(j);
                    for (int k = 0; k < classifyBo.getClassifyTwo().size(); k++) {
                        ClassifyBo classifyBo2 = classifyBo.getClassifyTwo().get(k);
                        if (classifyBo2.getId().equals(mLabelList.get(i).getId())) {
                            classifyBo2.setChecked(true);
                        }
                    }

                }
            }
        }

        mSmartRefesh.finishRefresh();

        if (mData == null) return;
        list = new ArrayList<>();
        for (int i = 0; i < mData.size(); i++) {
            LifeMenuSection lifeMenuSection = new LifeMenuSection(true, mData.get(i).getClassify(), false);
            list.add(lifeMenuSection);
            for (int j = 0; j < mData.get(i).getClassifyTwo().size(); j++) {
                LifeMenuSection lifeMenuSection2 = new LifeMenuSection(mData.get(i).getClassifyTwo().get(j));
                list.add(lifeMenuSection2);
            }

        }

        sectionAdapter = new ClassifyAdapter(list);
        mRvClassify.setAdapter(sectionAdapter);
        sectionAdapter.setOnItemChildClickListener(this);

    }

    @Override
    public void showExpert(List<SearchFriendBo.UserFriendBean> classifyBos) {

    }

    @Override
    public void showEmpty() {

    }

    @Override
    public void showError(String ex) {
        showMsg("showError" + ex);
        mSmartRefesh.finishRefresh();
    }


    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        initData();
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        ClassifyBo mySection = list.get(position).t;
        if (isSelect) {
            removeDuplicateWithOrder(mLabelList);
            if (mLabelList.size() >= 3) {

                for (int i = 0; i < mLabelList.size(); i++) {
                    if (mySection.getId().equals(mLabelList.get(i).getId())) {
                        mLabelList.remove(i);
                        mLabelAdpter.notifyDataSetChanged();
                    }
                }

                if (mLabelList.size() >= 3) {
                    T.showShort("最多只能选择三个标签!");
                    return;
                }


            } else {
                mLabelList.add(mySection);
                removeDuplicateWithOrder(mLabelList);
                if (mLabelList.size() > 3) {
                    T.showShort("最多只能选择三个标签!");
                    return;
                }

                mLabelAdpter.setNewData(mLabelList);
                mTvShowLabelCount.setText(Html.fromHtml("已选择标签：<font color=\"#2AA0F8\">" + mLabelAdpter.getData().size() + "</font>"));
            }

        } else {
            Intent intents = new Intent(this, QuestionListActivity.class);
            intents.putExtra("type_id2", mySection.getId());
            intents.putExtra("type_name", mySection.getClassify());
            startActivity(intents);
        }

    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        if (item.getItemId() == R.id.action_next) {
            if (mLabelList.size() > 3) {
                showMsg("最多只能选择三个标签！");
                return true;
            }
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putParcelableArrayList("labels", mLabelList);
            intent.putExtras(bundle); //将计算的值回传回去
            setResult(-1, intent);
            finish();
        }
        return false;
    }

    class LabelAdpter extends BaseQuickAdapter<ClassifyBo, BaseViewHolder> {

        public LabelAdpter() {
            super(R.layout.item_classfiy_label);
        }

        @Override
        protected void convert(BaseViewHolder helper, ClassifyBo item) {
            helper.setText(R.id.tv_classfly_label, item.getClassify());
        }

    }

    // 删除ArrayList中重复元素，保持顺序
    public static void removeDuplicateWithOrder(List list) {
        Set set = new HashSet();
        List newList = new ArrayList();

        for (Iterator iter = list.iterator(); iter.hasNext(); ) {
            Object element = iter.next();
            if (set.add(element)) {
                newList.add(element);
            } else {
                newList.remove(element);
            }
        }
        list.clear();
        list.addAll(newList);
    }
}
